<script setup lang="ts">
import { ref } from 'vue'
import { checkMobile } from '@/utils/validate'
import { addUserApi } from '@/api/user'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
const router = useRouter()
const userinfo = ref({
  username: '',
  password: '',
  mobile: '',
  avatar: '',
})

const userinfoRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 12, message: '请输入6~12位字符', trigger: 'blur' },
  ],
  mobile: [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (checkMobile(value)) {
          callback()
        } else {
          callback(new Error('手机号格式有误'))
        }
      },
      trigger: 'blur',
    },
  ],
}

// 新增用户方法
const addUser = async () => {
  const res = await addUserApi(userinfo.value)
  ElMessage.success('新增用户成功')
  router.push('/user')
}
</script>

<template>
  <el-card>
    <template #header> 用户创建 </template>

    <el-form
      :model="userinfo"
      :rules="userinfoRules"
      label-width="auto"
      size="large"
    >
      <el-form-item label="用户名" prop="username">
        <el-input
          placeholder="请输入用户名"
          v-model="userinfo.username"
        ></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          placeholder="请输入密码"
          v-model="userinfo.password"
        ></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input
          placeholder="请输入手机号"
          v-model="userinfo.mobile"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addUser">立即创建</el-button>
        <el-button>重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<style scoped lang="scss"></style>
